package com.huadao.cart_ccs.experiment.confirmBeforeCulture.rawMaterial;

import android.content.Context;
import android.support.v7.widget.DividerItemDecoration;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.SearchView;
import android.widget.Spinner;
import android.widget.TextView;

import com.huadao.cart_ccs.R;
import com.huadao.cart_ccs.base.BaseListDF;
import com.huadao.cart_ccs.base.BasePresenter;
import com.huadao.cart_ccs.common.TimeUtil;
import com.huadao.cart_ccs.common.adapter.CommonRecycleAdapter;
import com.huadao.cart_ccs.common.adapter.CommonViewHolder;
import com.huadao.cart_ccs.common.adapter.FooterHolder;
import com.huadao.cart_ccs.common.adapter.HeaderHolder;
import com.huadao.cart_ccs.common.adapter.onItemCommonClickListener;
import com.huadao.cart_ccs.common.popwindow.RockPop;
import com.huadao.cart_ccs.data.bean.Dispensing;
import com.huadao.cart_ccs.data.bean.Project;
import com.huadao.cart_ccs.data.bo.RawMaterialBO;
import com.huadao.cart_ccs.main.CartApplication;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

public class RawMaterialFrag extends BaseListDF implements IRawMaterialContract.IRawMaterialView {

    private List<Dispensing> rawMaterialBOList;
    //    private List<RawMaterialBO> confirmedList;
    private Button btn_confirm;
    private SearchView searchView;
    private EditText et_search;
    private RawMaterialPresenter presenter;
    private Spinner spinnerDay;
    private LinearLayout ll_day;
    private TextView dayText;
    private RockPop rockPop;

    public interface ConfirmRawMaterial {
        void onConfirmRawMaterial();
    }

    private ConfirmRawMaterial confirmRawMaterial;

    @Override
    public int getRecycleViewId() {
        return R.id.recycleView;
    }

    @Override
    public int getSwipeRefreshLayoutId() {
        return R.id.swipeRefreshLayout;
    }

    @Override
    protected void init() {
        rawMaterialBOList = new ArrayList<>();
        searchView = view.findViewById(R.id.searchView);
        spinnerDay=view.findViewById(R.id.spinner_day);
        searchView.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                searchView.setIconified(false);
            }
        });
        searchView.setOnSearchClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                presenter.search();
            }
        });

        btn_confirm = view.findViewById(R.id.btn_confirm);
        btn_confirm.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
//                if (!isAllConfirmed()) {
//                    showToast("请确认所有原材料");
//                    return;
//                }
                if (confirmRawMaterial != null) {
                    confirmRawMaterial.onConfirmRawMaterial();
                }
            }
        });
        presenter = new RawMaterialPresenter(this);
//        confirmedList=new ArrayList<>();
        et_search = view.findViewById(R.id.et_search);
        et_search.setOnEditorActionListener(new TextView.OnEditorActionListener() {
            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    et_search.requestFocus();
//                    String condition=v.getText().toString();
                    presenter.search();
                    return true;
                } else {
                    return false;
                }
            }
        });

        //设置天数选择
        List<String> dayList=new ArrayList<>();
        dayList.add("全部");

        Calendar now=Calendar.getInstance();
        now.setTime(new Date());
        Calendar projectStartTime=Calendar.getInstance();
        Date projectStart=getProjectStartTime();
        if(projectStart!=null){
            projectStartTime.setTime(projectStart);
            int daysBetween;
            int projectStartYear=projectStartTime.get(Calendar.YEAR);
            int nowYear=now.get(Calendar.YEAR);
            //项目如果在一年内
            if (projectStartYear==nowYear){
                daysBetween=now.get(Calendar.DAY_OF_YEAR)-projectStartTime.get(Calendar.DAY_OF_YEAR)+1;
            }else {
                daysBetween=now.get(Calendar.DAY_OF_YEAR)+projectStartTime.getActualMaximum(Calendar.DAY_OF_YEAR)-projectStartTime.get(Calendar.DAY_OF_YEAR)+1;
            }

            for(int i=0;i<daysBetween;i++){
                dayList.add("DAY"+(i+1));
            }
        }

        //适配器
        ArrayAdapter arr_adapter= new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, dayList);
        //设置样式
        arr_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        //加载适配器
        spinnerDay.setAdapter(arr_adapter);
        spinnerDay.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                if(i==0){
                    presenter.getRawMaterialList();
                }else {
                    presenter.getMaterialListByDay(i);
                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });

        presenter.checkDataSchedual();

        ll_day=view.findViewById(R.id.ll_day);
        dayText=view.findViewById(R.id.dayText);

        View contentView = LayoutInflater.from(getActivity()).inflate(R.layout.pop_material_state, null, false);
        RecyclerView rv_day=contentView.findViewById(R.id.rv_day);
        rv_day.setLayoutManager(new LinearLayoutManager(getActivity()));
        rv_day.setAdapter(new DayAdapter(getActivity(),dayList,R.layout.item_day_material));
        rockPop = new RockPop.PopupWindowBuilder(getActivity())
                .setView(contentView)
                .setDirection(RockPop.DIRECTION_BOTTOM)
                .create();

        ll_day.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                rockPop.show(ll_day);
            }
        });

    }

    @Override
    public String getSearchWord() {
        return et_search.getText().toString();
    }

    @Override
    public int getSelectedDay() {
//        if(spinnerDay.getSelectedItemPosition()==0){
//            return -1;
//        }else {
//            return spinnerDay.getSelectedItemPosition();
//        }
        return spinnerDay.getSelectedItemPosition();
    }

    private boolean isAllConfirmed() {
        if (rawMaterialBOList == null || rawMaterialBOList.size() == 0) {
            return true;
        } else {
            for (Dispensing rawMaterialBO : rawMaterialBOList) {
                if (!rawMaterialBO.isUse()) {
                    return false;
                }
            }
        }
        return true;
    }

    @Override
    protected RecyclerView.ItemDecoration setItemDecoration() {
        return new DividerItemDecoration(getActivity(), DividerItemDecoration.VERTICAL);
    }

    @Override
    protected CommonRecycleAdapter setAdapter() {
        return new RawMaterialAdapter(getActivity(), rawMaterialBOList, R.layout.item_rawmaterial);
    }

    @Override
    public RecyclerView.LayoutManager setLayoutManage() {
        return new LinearLayoutManager(getActivity());
    }

    @Override
    protected void loadData() {
        presenter.getRawMaterialList();
    }

    @Override
    protected void onRefreshData() {
        presenter.refresh();
    }

    @Override
    protected BasePresenter getPresenter() {
        return presenter;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.frag_raw_material;
    }

    @Override
    public void onRawMaterialList(List<Dispensing> dispensings) {
        setSwipeRefresh(false);
        rawMaterialBOList.clear();
        rawMaterialBOList.addAll(dispensings);
        notifyDataSetChanged();
    }

    @Override
    public String getProjectId() {
        return CartApplication.getInstance().getSystemProjectId();
    }

    @Override
    public Date getProjectStartTime() {
        Project project=CartApplication.getInstance().getSystemProject();
        if(project==null){
            return null;
        }
        return project.getStartTime();
    }

    @Override
    public void onSearchRawMaterialList(List<Dispensing> materialBOList) {
        setSwipeRefresh(false);
        rawMaterialBOList.clear();
        rawMaterialBOList.addAll(materialBOList);
        notifyDataSetChanged();
    }

    public void setConfirmRawMaterial(ConfirmRawMaterial confirmRawMaterial) {
        this.confirmRawMaterial = confirmRawMaterial;
    }

    class RawMaterialAdapter extends CommonRecycleAdapter<Dispensing> {

        public RawMaterialAdapter(Context context, List<Dispensing> dataList, int layoutId) {
            super(context, dataList, layoutId);
        }

        @Override
        protected void bindData(CommonViewHolder holder, Dispensing data) {

        }

        @Override
        protected void bindData(final CommonViewHolder holder, int position) {
            Dispensing data=rawMaterialBOList.get(position);
            holder.setText(R.id.tv_NO,String.valueOf(position+1));
            holder.setText(R.id.tv_name, data.getName());
            holder.setText(R.id.tv_batchNumber, data.getBatchCode());
            if (data.getExpirationDate() != null) {
                holder.setText(R.id.tv_sterilizationValidityTo,TimeUtil.log_sdf.format(data.getExpirationDate()));
            }
            holder.setText(R.id.tv_note, data.getRemark());
            if (data.isUse()) {
                holder.setText(R.id.btn_confirm, getString(R.string.receivedAlready));
                holder.setTextColor(R.id.btn_confirm,getResources().getColor(R.color.text_green));
            }else {
                holder.setText(R.id.btn_confirm, getString(R.string.notReceived));
                holder.setTextColor(R.id.btn_confirm,getResources().getColor(R.color.text_red));
            }
        }

        @Override
        protected void bindFooterData(FooterHolder holder) {

        }

        @Override
        protected void bindHeaderData(HeaderHolder holder) {

        }
    }

    class DayAdapter extends CommonRecycleAdapter<String>{

        public DayAdapter(Context context, List<String> dataList, int layoutId) {
            super(context, dataList, layoutId);
        }

        @Override
        protected void bindData(CommonViewHolder holder, String data) {
            holder.setText(R.id.text,data);
            holder.setCommonClickListener(new onItemCommonClickListener() {
                @Override
                public void onItemClickListener(int position) {
                    if(position==0){
                        presenter.getRawMaterialList();
                    }else {
                        presenter.getMaterialListByDay(position);
                    }
                    dayText.setText(dataList.get(position));
                    rockPop.dismiss();
                }

                @Override
                public void onItemLongClickListener(int position) {

                }
            });
        }

        @Override
        protected void bindFooterData(FooterHolder holder) {

        }

        @Override
        protected void bindHeaderData(HeaderHolder holder) {

        }
    }
}
